var proxy_list = $('.proxy-list'), global = {};

function append_tunnel (tunnel) {
    console.log ('tunnel = ' + tunnel);
    if (typeof tunnel === 'string') {
        tunnel = eval ('(' + tunnel + ')');
    }

    try {
        var li = $('<li class="clearfix"/>').attr ('data-tid', tunnel['id'])
            .on ('click', on_tunnel_click)
            .on ('dblclick', on_tunnel_dbl_click)
            .appendTo (proxy_list);
        update_tunnel_item (tunnel, li);
        if (!('tunnels' in global)) {
            global.tunnels = {};
        }
        global.tunnels [tunnel['id']] = tunnel;
    } catch (ex) {
        console.error (ex);
    }
}

function update_tunnel_item (tunnel, li) {
    $('<div class="pull-left connect-status"/>').addClass (tunnel ['connected'] ? 'connected' : 'disconnected').appendTo (li);
    var div = $('<div class="tunnel-info"/>').appendTo (li);
    $('<div class="tunnel-name"/>').text (tunnel ['name']).appendTo (div);
    var link = tunnel['server'] + ':' + tunnel ['service_port'] + ' &lt;=&gt; ' + tunnel ['peer'] + ':' + tunnel ['peer_port'];
    $('<div/>').html (link).appendTo (div);
}

function on_tunnel_update (tunnel) {
    console.log ('[on_tunnel_updated] tunnel = ' + tunnel);
    if (typeof tunnel === 'string') {
        tunnel = eval ('(' + tunnel + ')');
    }
    global.tunnels [tunnel.id] = tunnel;
    var li = $('.proxy-list>li[data-tid=' + tunnel.id + ']');
    if (li.length) {
        li.empty ();
        update_tunnel_item (tunnel, li);
    }
}

function on_tunnel_deleted (tid) {
    console.log ('tid = ' + tid);
    try {
        var li = proxy_list.find ('li[data-tid=' + tid + ']');
        if (li.length) {
            li.remove ();
        }
        if (('tunnels' in global) && (tid in global.tunnels)) {
            delete global.tunnels [tid];
            if (!global.tunnels.length) {
                delete global.tunnels;
            }
        }
    } catch (ex) {
        console.error (ex);
    }
}

function on_tunnel_connect_state_changed (tid, state) {
    console.log ('[on_tunnel_connect_state_changed] tid = ' + tid + ', connected = ' + state);
    var li = proxy_list.find ('li[data-tid=' + tid + ']'), icon = li.find ('.connect-status');
    console.log ('[on_tunnel_connect_state_changed] li.length = ' + li.length);
    if (li.length) {
        li.find ('.connecting').remove ();
        if ('connecting' === state) {
            var div = $('<div class="connecting pull-right" />').appendTo (li);
            $('<i class="fa fa-spinner fa-pulse fa-2x fa-fw" />').appendTo (div);
        }
        global.tunnels [tid].state = state;
        change_toolbar_state (global.tunnels [tid]);
    } else {
        console.log ('tunnel [' + tid + '] not found');
    }
}

function on_tunnel_dbl_click () {
    bridge.require ('btn-edit', $(this).attr ('data-tid'));
}

function on_tunnel_click () {
    $('.proxy-list>li[data-selected]').removeAttr ('data-selected').removeClass ('selected');
    var self = $(this).attr ('data-selected', 'true').addClass ('selected'),
        tunnel = global.tunnels [self.attr ('data-tid')];
    if (tunnel) {
        change_toolbar_state (tunnel);
    }
}

function change_toolbar_state (tunnel) {
    if (tunnel) {
        $('.btn-edit, .btn-remove').removeClass ('disabled');
        var btn_connected    = $('.btn-connected'),
            btn_disconnected = $('.btn-disconnected');
        switch (tunnel.state) {
            case 'connected':
                btn_connected.addClass ('disabled');
                btn_disconnected.removeClass ('disabled');
                break;

            case 'disconnected':
            default:    // 初始状态和未连接是一样的
                btn_connected.removeClass ('disabled');
                btn_disconnected.addClass ('disabled');
                break;

            case 'connecting':
                $('.btn-edit, .btn-remove, .btn-disconnected, .btn-connected').addClass ('disabled');
                break;
        }
    }
}

function on_page_load (data) {
    if (typeof data === 'string') {
        data = eval ('(' + data + ')');
    }
    if ('tunnels' in data) {
        console.log ('we found tunnels, apply them.');
        var tunnels = data ['tunnels'];
        if (tunnels && tunnels.length) {
            global.tunnels = {};
            for (var i = 0; i < tunnels.length; i ++) {
                global.tunnels [tunnels[i].id] = tunnels [i];
                append_tunnel (tunnels [i]);
            }
        }
    }
}

function update_ui () {
    var locale = LOCALE || 'en_US', res;
    console.log ('updating ui with locale: ' + locale);
    res = R[locale] || R ['en_US'];
    res = res.index.labels;
    if (!res) {
        return;
    }

    for (var k in res) if (res.hasOwnProperty (k)) {
        $('.' + k).attr ('title', res [k]);
    }
}

// javascript local on-load handler
$(function () {
    // attach the window resize handler
    $(window).on ('resize', function () {
        var toolbar = $('.tool-bar'), top = toolbar.offset ().top + toolbar.height (), H = $(window).height ();
        $('.proxy-list').css ({height:H-top});
    }).trigger ('resize');

    function find_tid () {
        return $('.proxy-list>li[data-selected]').attr ('data-tid');
    }

    $('.tool-button').on ('click', function () {
        var self = $(this), action, params;
        if (self.hasClass ('disabled')) {
            return;
        }

        action = self.attr ('data-action');
        switch (action) {
            case 'btn-remove':
                var tid = find_tid (), tunnel = global.tunnels [tid];
                console.log ("======================");
                console.log ("tid    = " + tid);
                console.log ("tunnel = " + tunnel);
                console.log ("======================");
                if (tunnel) {
                    try {
                        $.Alert.warn (RS (R, 'index.messages.confirm-delete', {name: tunnel.name}), 'after-close', function () {
                            if (bridge.require (action, tid)) {
                                on_tunnel_deleted (tid);
                            }
                        });
                    } catch (ex) {
                        console.error (ex);
                    }
                }
                return;

            case 'btn-edit':
            case 'btn-connected':
            case 'btn-disconnected':
                params = find_tid ();
                try {
                    on_tunnel_connect_state_changed(params, 'connecting');
                } catch (e) {
                    console.error (e);
                }
                break;

            default:
                params = '';
                break
        }
        console.log ('invoking java with {action = "' + action + '" and params = "' + params + '"');
        bridge.require (action, params);
    });
});